﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using ML.Utils;

namespace ML.WebApi.Controllers
{
    /// <summary>
    /// 图片上传
    /// </summary>
    public class ImageUploadController : BaseApiController
    {
        private const string Extensions = "PNG,BMP,JPEG,JPG,GIF,ICON";
        private readonly ILogger logger = new NLogLogger();
        private readonly string https = "https://liteapi.xluo.com.cn/Upload/Image/";

        /// <summary>
        /// 图片文件上传
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("api/imageupload")]
        public async Task<IHttpActionResult> Post()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                return Json(new { code = 400, msg = "do'not receive file" });
            }
            string uploadFolderPath = HttpContext.Current.Server.MapPath("~/Upload/Image");

            //如果路径不存在，创建路径  
            if (!Directory.Exists(uploadFolderPath))
                Directory.CreateDirectory(uploadFolderPath);

            List<string> files = new List<string>();
            var provider = new WithExtensionMultipartFormDataStreamProvider(uploadFolderPath, Guid.NewGuid().ToString());
            try
            {
                // Read the form data.  
                await Request.Content.ReadAsMultipartAsync(provider);

                // This illustrates how to get the file names.  

                foreach (var file in provider.FileData)
                {
                    var extensionName = file.Headers.ContentDisposition.FileName.Split('.')[1].Trim('"');
                    //扩展名判断
                    if (!Extensions.Split(',').Contains(extensionName.ToUpper()))
                    {
                        return Json(new { code = 400, msg = "please upload image file" });
                    }

                    //接收文件  
                    files.Add(Path.GetFileName(file.LocalFileName));
                }
            }
            catch (Exception ex)
            {
                logger.Debug(ex.Message);
                return Json(new { code = 400, msg = "upload error" });
            }
            return Json(new { code = 200, data = https + string.Join(",", files) });
        }

        public class WithExtensionMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
        {
            public string guid { get; set; }

            public WithExtensionMultipartFormDataStreamProvider(string rootPath, string guidStr)
                : base(rootPath)
            {
                guid = guidStr;
            }

            public override string GetLocalFileName(System.Net.Http.Headers.HttpContentHeaders headers)
            {
                string extension = !string.IsNullOrWhiteSpace(headers.ContentDisposition.FileName) ? Path.GetExtension(GetValidFileName(headers.ContentDisposition.FileName)) : "";
                return guid + extension;
            }

            private string GetValidFileName(string filePath)
            {
                char[] invalids = System.IO.Path.GetInvalidFileNameChars();
                return String.Join("_", filePath.Split(invalids, StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.');
            }
        }
    }
}